#include "text_card_widget.h"
#include "ui_text_card_widget.h"

TextCardWidget::TextCardWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TextCardWidget)
{
    ui->setupUi(this);
    initUi();
    initEvents();
}

TextCardWidget::~TextCardWidget()
{
    delete ui;
}

void TextCardWidget::setTitle(const QString &title)
{
    ui->title->setText(title);
}

void TextCardWidget::setText(const QString &text)
{
    ui->textEdit->setText(text);
}

QString TextCardWidget::getText()
{
    return ui->textEdit->toPlainText();
}

void TextCardWidget::initUi()
{
    ui->cancelBtn->hide();
    ui->saveBtn->hide();
    ui->editBtn->show();
    ui->textEdit->setReadOnly(true);
    initTextEditStyle();
}

void TextCardWidget::initEvents()
{
    connect(ui->editBtn, &QPushButton::clicked, this, [=]() {
        m_oldText = ui->textEdit->toPlainText();
        ui->textEdit->setReadOnly(false);
        ui->cancelBtn->show();
        ui->saveBtn->show();
        ui->editBtn->hide();
    });

    connect(ui->saveBtn, &QPushButton::clicked, this, [=]() {
        m_oldText.clear();
        ui->textEdit->setReadOnly(true);
        ui->editBtn->show();
        ui->cancelBtn->hide();
        ui->saveBtn->hide();
        emit(saveBtnClicked());
    });

    connect(ui->cancelBtn, &QPushButton::clicked, this, [=]() {
        ui->textEdit->setText(m_oldText);
        m_oldText.clear();
        ui->textEdit->setReadOnly(true);
        m_oldText.clear();
        ui->editBtn->show();
        ui->cancelBtn->hide();
        ui->saveBtn->hide();
    });
}

void TextCardWidget::initTextEditStyle()
{
    QFont font;
    font.setFixedPitch(true);
    font.setPointSize(10);

    const int tabStop = 4;  // 4 characters
    QFontMetrics metrics(font);

    ui->textEdit->setFont(font);
    ui->textEdit->setTabStopDistance(tabStop * metrics.averageCharWidth());
}
